package com.gf.user.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.gf.base.dao.impl.BaseDaoImpl;
import com.gf.base.type.Activity;
import com.gf.base.type.LicenseState;
import com.gf.base.type.Role;
import com.gf.base.type.SafeFactor;
import com.gf.common.bean.Page;
import com.gf.user.dao.UserBaseDao;
import com.gf.user.mapper.UserMapper;
import com.gf.user.model.User;

@Service("userBaseDao")
public class UserBaseDaoImpl extends BaseDaoImpl implements UserBaseDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * insert into user
	 * (uuid,nickname,email,password,idNumber,realName,lastLoginIp,lastLoginTime
	 * ,idPath,licensePath,sex,activity,role,major) values
	 * (?,?,?,?,?,?,?,current_timestamp,?,?,?,?,?,?)
	 */
	@Value("${userBaseDao.insertSql}")
	private String insertUserSql;

	/**
	 * userBaseDao.queryByIdNumberSql=select * from user where idNumber=? and
	 * password=? limit 1
	 */
	@Value("${userBaseDao.queryByIdNumberSql}")
	private String queryByIdNumberSql;

	/**
	 * userBaseDao.queryUserByEmailSql=select * from user where email=? and
	 * password=? limit 1
	 */
	@Value("${userBaseDao.queryUserByEmailSql}")
	private String queryUserByEmailSql;

	/**
	 * select * from user where email=?
	 */
	@Value("${userBaseDao.queryEmailExistSql}")
	private String queryEmailExistSql;

	/**
	 * select * from user where email=? and idNumber=?
	 */
	@Value("${userBaseDao.queryEmailIdNumberExistSql}")
	private String queryEmailIdNumberExistSql;

	/**
	 * update user set password=? where id=?
	 */
	@Value("${userBaseDao.updatePasswdSql}")
	private String updatePasswdSql;

	/**
	 * update user set activity=? where id=?
	 */
	@Value("${userBaseDao.updateActivitySql}")
	private String updateActivitySql;

	@Value("${userBaseDao.updateLicenseStateSql}")
	private String updateLicenseStateSql;

	/**
	 * userBaseDao.deleteUserSql=delete from user where id=?
	 */
	@Value("${userBaseDao.deleteUserSql}")
	private String deleteUserSql;

	/**
	 * select * from user where id=?
	 */
	@Value("${userBaseDao.queryUserByIdSql}")
	private String queryUserByIdSql;

	/**
	 * select * from user order by id desc limit 1
	 */
	@Value("${userBaseDao.queryLatestUserSql}")
	private String queryLatestUserSql;

	/**
	 * select * from user where createtime>?
	 */
	@Value("${userBaseDao.queryUserByCreatetimeSql}")
	private String queryUserByCreatetimeSql;

	/**
	 * select * from user
	 */
	@Value("${userBaseDao.queryAllBaseUsersSql}")
	private String queryAllBaseUsersSql;

	/**
	 * select count(1) from user
	 */
	@Value("${userBaseDao.queryUserNumberSql}")
	private String queryUserNumberSql;

	/**
	 * select * from user where nickname=?
	 */
	@Value("${userBaseDao.queryUserByNicknameSql}")
	private String queryUserByNicknameSql;

	@Value("${userBaseDao.updateCareCountSql}")
	private String updateCareCountSql;

	@Value("${userBaseDao.updateFansCountSql}")
	private String updateFansCountSql;

	@Value("${userBaseDao.queryAllUserNumberSql}")
	private String queryAllUserNumberSql;

	@Value("${userBaseDao.queryAllUserSql}")
	private String queryAllUsersSql;

	/**
	 * select content from about where id in (select max(id) from about)
	 */
	@Value("${userBaseDao.queryAboutContentSql}")
	private String queryAboutContentSql;

	@Override
	public long insert(String uuid, String nickname, String email,
			String password, String idNumber, String realName, String idPath,
			String licensePath, String sex, String role, String ip,
			String major, SafeFactor safeFactor) {
		return this.insertWithIdReturn(insertUserSql, new Object[] { uuid,
				nickname, email, password, idNumber, realName, ip, idPath,
				licensePath, sex, Activity.INACTIVE.toString(), role, major,
				safeFactor.toString() });
	}

	@Override
	public User queryByIdNumber(String idNumber, String password) {
		ArrayList<User> users = new ArrayList<User>();
		users = (ArrayList<User>) jdbcTemplate.query(queryByIdNumberSql,
				UserMapper.getMapper(), idNumber, password);
		if (users == null || users.size() <= 0) {
			return null;
		} else {
			return users.get(0);
		}

	}

	@Override
	public User queryByEmail(String email, String password) {
		ArrayList<User> users = new ArrayList<User>();
		users = (ArrayList<User>) jdbcTemplate.query(queryUserByEmailSql,
				UserMapper.getMapper(), email, password);
		if (users == null || users.size() <= 0) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@Override
	public User queryEmailExist(String email) {
		ArrayList<User> users = new ArrayList<User>();
		users = (ArrayList<User>) jdbcTemplate.query(queryEmailExistSql,
				UserMapper.getMapper(), email);
		if (users == null || users.size() <= 0) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@Override
	public User queryEmailIdNumberExist(String email, String idNumber) {
		ArrayList<User> users = new ArrayList<User>();
		users = (ArrayList<User>) jdbcTemplate.query(
				queryEmailIdNumberExistSql, UserMapper.getMapper(), email,
				idNumber);
		if (users == null || users.size() <= 0) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@Override
	public void updatePasswd(long id, String newPasswd) {
		jdbcTemplate.update(updatePasswdSql, newPasswd, id);
	}

	@Override
	public boolean updateActivity(long id, Activity activity) {
		int result = jdbcTemplate.update(updateActivitySql,
				activity.toString(), id);
		return result > 0 ? true : false;
	}

	@Override
	public void deleteUser(long id) {
		jdbcTemplate.update(deleteUserSql, id);
	}

	@Override
	public User queryUserById(long id) {
		ArrayList<User> users = new ArrayList<User>();
		users = (ArrayList<User>) jdbcTemplate.query(queryUserByIdSql,
				UserMapper.getMapper(), id);
		if (users == null || users.size() <= 0) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@Override
	public User queryLatestUser() {
		ArrayList<User> users = new ArrayList<User>();
		users = (ArrayList<User>) jdbcTemplate.query(queryLatestUserSql,
				UserMapper.getMapper());
		if (users == null || users.size() <= 0) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@Override
	public List<User> queryUserByCreatetime(Date date) {
		SimpleDateFormat formattime = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		String dateStr = formattime.format(date);
		// 数据库时间的比较格式要一致
		String dateFormatStr = "date_format('" + dateStr
				+ "','%Y-%m-%d %H:%i:%s')";

		return jdbcTemplate.query(queryUserByCreatetimeSql,
				UserMapper.getMapper(), dateFormatStr);
	}

	@Override
	public List<User> queryAllBaseUsers(int currentPage, int pageSize, Role role) {
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(pageSize);

		return getPaginationResult(queryAllBaseUsersSql, page,
				UserMapper.getMapper(), role.toString());
	}

	@Override
	public int queryAllBaseUserNumber(Role role) {

		return jdbcTemplate.queryForInt(queryUserNumberSql, role.toString());
	}

	@Override
	public User queryUserByNickname(String nickname) {
		ArrayList<User> users = new ArrayList<User>();
		users = (ArrayList<User>) jdbcTemplate.query(queryUserByNicknameSql,
				UserMapper.getMapper(), nickname);
		if (users == null || users.size() <= 0) {
			return null;
		} else {
			return users.get(0);
		}
	}

	@Override
	public boolean updateCareCount(long userId, int careCount) {
		jdbcTemplate.update(updateCareCountSql, careCount, userId);
		return true;
	}

	@Override
	public boolean updateFansCount(long userId, int funCount) {
		jdbcTemplate.update(updateFansCountSql, funCount, userId);
		return true;
	}

	@Override
	public List<User> queryAllUsers(int currentPage, int pageSize) {
		Page page = new Page();
		page.setCurpage(currentPage);
		page.setPageSize(pageSize);

		return getPaginationResult(queryAllUsersSql, page,
				UserMapper.getMapper());
	}

	@Override
	public int queryAllUserNumber() {
		return jdbcTemplate.queryForInt(queryAllUserNumberSql);
	}

	@Override
	public boolean updateLicenseState(long id, LicenseState licenseState) {
		jdbcTemplate.update(updateLicenseStateSql, licenseState.toString(), id);
		return true;
	}

	@Override
	public String queryAboutContent() {
		return jdbcTemplate.queryForObject(queryAboutContentSql, String.class);
	}

}
